package com.ruoyi.lvlian.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.ProductCategory;
import com.ruoyi.lvlian.dto.ProductCategoryDto;
import com.ruoyi.lvlian.mapper.ProductCategoryMapper;
import com.ruoyi.lvlian.service.IProductCategoryService;
import com.ruoyi.lvlian.vo.ProductCategoryFlatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 产品分类Service业务层处理
 *
 * @author lvlian
 * @date 2025-04-15
 */
@Service
public class ProductCategoryServiceImpl implements IProductCategoryService {
    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    /**
     * 查询产品分类
     *
     * @param id 产品分类主键
     * @return 产品分类
     */
    @Override
    public ProductCategory selectProductCategoryById(String id, String level) {
        return productCategoryMapper.selectProductCategoryById(id, level);
    }

    /**
     * 查询产品分类列表
     *
     * @param productCategory 产品分类
     * @return 产品分类
     */
    @Override
    public List<ProductCategory> selectProductCategoryList(ProductCategoryDto productCategory) {
        return productCategoryMapper.selectProductCategoryList(productCategory);
    }

    /**
     * 新增产品分类
     *
     * @param productCategory 产品分类
     * @return 结果
     */
    @Override
    public int insertProductCategory(ProductCategory productCategory) {
        if (null == productCategory.getCode() || 5 > productCategory.getCode().length()) {
            productCategory.setCode(Seq.getId());
        }
        productCategory.setCreateUser(SecurityUtils.getUsername());
        productCategory.setViewFlag(true);
        return productCategoryMapper.insertProductCategory(productCategory);
    }

    /**
     * 修改产品分类
     *
     * @param productCategory 产品分类
     * @return 结果
     */
    @Override
    public int updateProductCategory(ProductCategory productCategory) {
        productCategory.setCreateDate(DateUtils.getCurrentTime());
        if (null == productCategory.getCode() || 5 > productCategory.getCode().length()) {
            productCategory.setCode(Seq.getId());
        }
        if (productCategory.getId() == null) {
            return insertProductCategory(productCategory);
        } else {
            return productCategoryMapper.updateProductCategory(productCategory);
        }
    }

    /**
     * 批量删除产品分类
     *
     * @param ids 需要删除的产品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoryByIds(Long[] ids) {
        return productCategoryMapper.deleteProductCategoryByIds(ids);
    }

    /**
     * 删除产品分类信息
     *
     * @param id 产品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoryById(Long id) {
        return productCategoryMapper.deleteProductCategoryById(id);
    }


    @Override
    public List<ProductCategory> getCategoryTree(ProductCategoryDto productCategory) {
        if (null == productCategory.getViewFlag()) {
            productCategory.setViewFlag(true);
        }
        // 一次性查出所有分类数据
        List<ProductCategory> allCategories = productCategoryMapper.selectProductCategoryList(productCategory);

        // 找出 level = 1 的根节点
        List<ProductCategory> rootList = allCategories.stream()
                .filter(c -> "1".equals(c.getLevel()))
                .collect(Collectors.toList());

        // 构建子树结构
        for (ProductCategory root : rootList) {
            buildTree(root, allCategories);
        }

        return rootList;
    }

    @Override
    public List<ProductCategoryFlatVo> queryFlat(ProductCategoryDto productCategory) {
        List<ProductCategoryFlatVo> list = productCategoryMapper.queryFlat(productCategory);
        return list;
    }

    @Override
    public int deleteProductCategory(ProductCategoryDto productCategory) {
        return productCategoryMapper.deleteProductCategory(productCategory);
    }

    /**
     * 构建树结构，递归填充每个节点的 child 字段
     */
    private void buildTree(ProductCategory parent, List<ProductCategory> allCategories) {
        String nextLevel = String.valueOf(Integer.parseInt(parent.getLevel()) + 1);
        List<ProductCategory> children = findChildrenByParentIdAndLevel(parent.getId(), nextLevel, allCategories);
        parent.setChild(children);
        for (ProductCategory child : children) {
            buildTree(child, allCategories); // 递归设置子节点
        }
    }


    /**
     * 根据 parentId 和 level，从已查询的 allCategories 中筛选子节点
     */
    public List<ProductCategory> findChildrenByParentIdAndLevel(Long parentId, String level, List<ProductCategory> allCategories) {
        return allCategories.stream()
                .filter(c -> Objects.equals(c.getParentId(), parentId) && level.equals(c.getLevel()))
                .collect(Collectors.toList());
    }


}
